package 并发Map集合;

import java.util.Hashtable;
import java.util.concurrent.ConcurrentHashMap;

public class HashMapDemo1 {

//    public static Hashtable<String , Integer>  maps = new Hashtable<>();    //线程安全，悲观锁，性能差，已经被淘汰
    public static ConcurrentHashMap<String , Integer> maps = new ConcurrentHashMap<>();  //CAS机制+局部锁，综合性能好，安全

    public static void main(String[] args) {

    //        创建线程任务
    MyRunnable1 myRunnable = new MyRunnable1();

    Thread thread0 = new Thread(myRunnable,"线程0");
    Thread thread1 = new Thread(myRunnable,"线程1");

        thread0.start();
        thread1.start();

        try {
//            主线程遇到这条语句，会让出CPU资源，并且不再和线程0、线程1争夺资源，直到线程0、1执行结束
        thread0.join();
        thread1.join();
    } catch (Exception e) {
        e.printStackTrace();
    }

//        join方法确保线程执行完，再最后统计集合中的元素
        System.out.println("元素个数是:"+maps.size());

}

}

class MyRunnable1 implements Runnable {

    @Override
    public void run() {
        for (int i = 0 ; i < 500000 ; i++) {

//            通过类名调用集合，添加数据
//            键需要唯一，用线程名加数字，可以保证键的唯一性
            HashMapDemo1.maps.put(Thread.currentThread().getName()+i , i);
        }
    }
}